#!/usr/bin/env python

import os
import wx
import app
import dialog
import thread
import component as c

from _base import Base

class Main(Base):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    _folder = ''
    
    def __init__(self, view, interactor):
        super(Main, self).__init__(view, interactor)
        self.readFolder()
        self.populateFiles(self._folder)
        self.populateManga()
        self.view.form.language.Value = 'English'
        self.view.form.name.Value = 'Hayate'
        self.view.form.email.Value = 'hayate@ashitahadochida.site11.com'
        
    def onClose(self):
        self.writeFolder()
        super(Main, self).onClose()
        
    def close(self):
        self.view.Close()
    
    def readFolder(self):
        self._folder = app.Config().Read('%s/Folder' % self.view.Name, '')
    
    def writeFolder(self):
        key = '%s/Folder' % self.view.Name
        app.Config().Write(key, self._folder)
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()
        
    def browse(self):
        folder = self.view.dirDialog(defaultPath=self._folder,
                                     style=wx.DD_DIR_MUST_EXIST)
        if folder: self.populateFiles(folder)
    
    def populateFiles(self, folder):
        if not os.path.lexists(folder): return
        
        self._folder = folder
        exts = ('png', 'jpg', 'jpeg')
        filenames = os.listdir(folder)
        files = []
        for filename in filenames:
            name, ext = os.path.splitext(filename)
            ext = ext.lower()[1:]
            if ext in exts:
                files.append(filename)
        self.view.form.files.values = files
    
    def populateManga(self):
        hayate = c.Hayate()
        r = hayate.get('api/manga')
        if not r: return
        
        self.view.form.manga.values = r['data']
        
    def populateChapter(self, manga):
        params = {'Chapter[mangaId]': manga['id']}
        hayate = c.Hayate()
        r = hayate.post('api/chapter/search', params)
        self.view.form.chapter.values = r['data']

    def upload(self):
        total = len(self.view.form.files.selection)
        self.view.progressDialog('Uploading...', 'Uploading', total)
        thread.start_new_thread(self.uploading, ())
    
    def uploading(self):
        form = self.view.form
        manga = form.manga.value
        chapter = form.chapter.value
        sequence = int(form.sequence.Value)
        subSequence = form.subSequence.Value
        language = form.language.Value
        name = form.name.Value
        email = form.email.Value
        hayate = c.Hayate()
        counter = 0;
        for file in self.view.form.files.selection:
            message = 'Uploading %s...' % file
            wx.CallAfter(self.view.updateProgress, counter, message)
            params = {'Chapter[mangaId]': chapter['mangaId'],
                      'Chapter[id]': chapter['id'],
                      'Page[sequence]': sequence,
                      'Page[subSequence]': subSequence,
                      'Language[value]': language,
                      'Language[name]': name,
                      'Language[email]': email}
            path = os.path.join(self._folder, file)
            r = hayate.post('api/language', params, path)
            counter += 1
            message = 'Uploading %s completed.' % file
            wx.CallAfter(self.view.updateProgress, counter, message)
            if not r['data']['ids']: break
            sequence += 1
            subSequence = ''
        
        wx.CallAfter(self.view.idle)
        form.sequence.Value = '%s' % sequence
        form.subSequence.Value = ''
        
        if not r['data']['ids']:
            self.view.messageDialog('Could not upload file %s.' % file,
                                    'Error')